import 'dart:math';

import 'package:get/get.dart';
import 'package:jydoctorflutter/net/api.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../model/home_headimageModel.dart';

class HomeMainLogic extends GetxController {
  RxList<homeHeadImageModel> imageModels = <homeHeadImageModel>[].obs;
  //刷新
  RefreshController homeRefreshController = RefreshController(initialRefresh: true);
  int currentPage = 1;
  int pageSize = 10;
  int totalPages = 0;
  int totalRecords = 0;
  //数据源
  RxList<homeHeadImageModel> invoiceList = <homeHeadImageModel>[].obs;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    loadData();
    loadListData(isRefresh: true); // 获取数据并刷新
  }
  @override

  void loadData() {

    Map<String, dynamic> params = {
      "categoryId": 1,
      "page":1,
      "pageSize":10,
    };
    Api.getListImageForApp(params).then((json) {

       if (json["items"] != null){
         print("0909===${json["items"]}");
         var itemList = json["items"] as List;
           // imageModels = itemList.map<homeHeadImageModel>((e) => homeHeadImageModel.fromJson(e)).toList() ?? [];
           imageModels.assignAll(itemList.map((e) => homeHeadImageModel.fromJson(e)).toList());
           print("imageModels.length=${imageModels.length}");
           }
       }
    );
  }

  void loadListData({bool isRefresh = false}) {
    print("9999999");
    Map<String, dynamic> params = {
      "categoryId": 2,
      "page":currentPage,
      "pageSize":10,
    };
    Api.getListImageForApp(params).then((json) {

      if (json["items"] != null){
        print("0909===${json["items"]}");
        var itemList = json["items"] as List;
        var arr = <homeHeadImageModel>[];
        arr = itemList.map((e) => homeHeadImageModel.fromJson(e)).toList();
        // arr.assignAll(itemList.map((e) => homeHeadImageModel.fromJson(e)).toList());
        print("arr == ${arr.length}");
        if (isRefresh) {
          // 下拉刷新时，清空并加载新数据
          invoiceList.clear();
        }
        invoiceList.addAll(arr);
        // invoiceList
        // 刷新完成或加载完成
        homeRefreshController.refreshCompleted();
        homeRefreshController.loadComplete();
        if (arr.length < pageSize) {
          // 如果返回的数据少于每页数量，表示没有更多数据
          homeRefreshController.loadNoData();
        }
      }
    }
    ).catchError((error) async {
      homeRefreshController.refreshFailed();
      homeRefreshController.loadFailed();
    });
  }

  // 下拉刷新逻辑
  void onRefresh() async {
    print("*********下拉");
    currentPage = 1; // 重置为第一页
    loadListData(isRefresh: true); // 获取数据并刷新
  }

  // 上拉加载更多逻辑
  void onLoading() async {
    print("*********上拉");
    currentPage++; // 增加当前页数
    loadListData(isRefresh: false); // 获取下一页数据并追加
  }
}
